iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0

定義函式的幾種方式

  • Function declaration
    會 hoist 到頂端
add(1,2); // 因為 function declaration hoist 的關係,所以可被執行

function add(a,b){
    return a+b;
}
  • Function expression
    不會 hoist 到頂端
add(1,2); // 會出現 add is not defined

const add = function(a,b){
    return a+b;
}

scope 作用域

  • 每一個綁定變數都有其作用範圍,在這個範圍/區塊內才能看見變數
  • 變數能被哪些區塊看到,取決於變數本身在程式碼內的區塊位置,每個區域範圍又能看到自身所處的整個區域範圍,全域則能看到所有範圍,這種決定變數能見度的方法稱為『詞彙範圍(lexical scope)』
  • 函式建立出作用域,意即函式(function)會建立自身的作用域(function scope)

javascript 的 scope 為 static scoping,意即在函式建立時,作用域就被確定了
現在多數的程式語言都是 static scoping 為主

global scope

let variable_in_global = 10;

console.log(variable_in_global); // 10

function scope

function doSomething(){
    let variable_in_function_scope = "can only access in function scope";
}

console.log(variable_in_function_scope); // variable_in_function_scope is not defined

引入新的作用域 introducing a new scope

有時候會需要引入新的作用域,像是要避免變數成為全域變數
這時候可以藉由 **IIFE (immediately invoked function expression) ** 來達成,一種將函式以類似block 使用的模式(using function in a block-like manner)

因為函式會建立自身的作用域

(function () { // open IIFE
    let tmp = ...; // not a global variable
}());

這樣 tmp 就不會是 global variable

arrow function

主要可減少程式碼長度,但需要注意的是 arrow function not bind their own this keyword
arrow function 的 this 是由建立的作用域繼承(inherit)而來

如果在 global scope 內建立 arrow function,則 this 會是 window object

const doSomething = () => {
    console.log(this); // this -> window object
};

如果在 object 內建立的 arrow function,其 this 則為建立的作用域繼承來,所以便會是 object

let worker = {
    name: "James",
    workerMethod() {
        const greeting = () => console.log(`${this.name} says hello`);
        greeting();
    },
};

worker.workerMethod(); // James says hello

預設函式的參數/選擇性參數 default parameter / optional parameter

提供函式的預設參數,直接在 curly braces 內 assign value

function (salary=28590 , bonus){
    console.log(`薪水有:${salary + bonus}元`)
}

當傳入函式的 parameter 過多,會自動忽略
當傳入函式的 parameter 太少,則會用 undefined 來補足缺失的參數

檢查參數長度是否符合函式需求 check length of parameter

善用 arguments.length

function pair(a,b){
    if (arguments.length !== 2){
        console.error("Need exactly 2 arguments");
    }
    ...
}

純函式與副作用 pure function & side effect

純函式:

  • 不會改變任何外部狀態的函式,特性為只要傳入相同的parameter,就會得到完全相同的結果
  • 必定會有回傳值(returned value),但未必都有return關鍵字,像單行的arrow function可以省略 return 而回傳值

帶有 return 的 pure function

function add(a,b){
    return a+b;
}

沒有 return 的 pure function

const add = (a,b)=> a+b

副作用:

會改變外部狀態的都可稱之為副作用,如:console, modified global variables, network request..

let total = 0;
function addToTotal(num){
    total += num;
}

上一篇
Chapter 2 練習題-day3
下一篇
Chapter 3 函式 Function_2(Closure/Recursive)-day5
系列文
溫故而知新:Eloquent Javascript 閱讀筆記5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言